package com.lotter.api.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lotter.api.service.MobileCodeService;
import com.lotter.api.service.OnlineUserService;
import com.lotter.api.service.SmsService;
import com.lotter.api.service.UserAccountService;
import com.lotter.common.context.YcContext;
import com.lotter.common.enumobject.SiteMessageFormat;
import com.lotter.common.exception.LotterCusException;
import com.lotter.common.util.RoomUtil;
import com.lotter.common.util.StringUtil;
import com.lotter.invocation.StaticDataContext;
import com.lotter.model.user.UserAccount;

/**
 * 登录前使用
 * @author zhangzechi
 *
 */
@Controller
public class IndexController extends BaseController {
	
	@Autowired
	private UserAccountService userAccountService ;
	
	@Autowired
	private SmsService smsService;

	@Autowired
	private MobileCodeService mobileCodeService ;
	
	
	@Autowired
	private OnlineUserService onlineUserService ;
	
	//测试使用
	@RequestMapping(value = "" ,method =RequestMethod.GET)
	public String webcome(HttpServletRequest request){
		System.out.println("nihao  再试一次");
		System.out.println("要打印出来啊我会疯的");
		logger.error("要打印出来一次啊");
		return "index";
	}
	
	
	@ResponseBody
	@RequestMapping(value = "webcome" ,method =RequestMethod.GET)
	public  Map<String, Object> webcome(@RequestParam(value ="token",required = false) String token){
		if(StringUtil.isBlank(token)){
			return ajaxLotterUser("请进行登录");
		}
		Long uid = StaticDataContext.onLineUid(token);
		onlineUserService.updateOnlineUser(uid);
		return null;
		
	}
	
	/**
	* @Title: VerifyMobile 
	* @Description: 验证手机号码是否可以注册
	* @param @param mobile 手机号码
	* @param @return    设定文件 
	* @return Map<String,Object>    返回类型 
	* @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/verifyMobile" ,method =RequestMethod.POST)
	public Map<String, Object> VerifyMobile(@RequestParam(value="mobile",required=true) 
	        String mobile){
		if(StringUtil.isBlank(mobile))
			return ajaxLotterStage("手机号码不能为空");
		
		if (mobile.trim().length() != 11) 
			return ajaxLotterStage("手机号码位数不是11位");
		
		if (!mobile.matches(YcContext.Mobile_PARTTEN))
			return ajaxLotterStage( "手机号码不符合规则");
		
		Boolean bool = false ;
		try {
			bool = userAccountService.isExistUserAccountByMobile(mobile);
			if(!bool){
				bool = mobileCodeService.whether(mobile);
				if(bool){
					return ajaxLotterStage("手机验证码已经发送过不要重复发送");
				}
				SiteMessageFormat siteMessageFormat = SiteMessageFormat.REGISTER_NOTICE;
				smsService.sendSms(mobile, siteMessageFormat);
				return ajaxLotterSuccess();
			}else{
				return ajaxLotterUser("号码已经存在，请进行登录");
			}
		} catch (Exception e) {
			logger.error("验证手机号码有误  请检查");
			return ajaxLotterServer("验证手机号码有误  请联系管理员");
		}
		
	}

	/**
	 *  验证手机  并发送验证码---- 找回密码使用  
	 */
	@ResponseBody
	@RequestMapping(value = "/backPwd" ,method =RequestMethod.POST)
	public Map<String,Object> backPwd(@RequestParam(value="mobile",required=true)String mobile){
		if(StringUtil.isBlank(mobile))
			return ajaxLotterStage("手机号码不能为空");
		
		if (mobile.trim().length() != 11) 
			return ajaxLotterStage("手机号码位数不是11位");
		
		if (!mobile.matches(YcContext.Mobile_PARTTEN))
			return ajaxLotterStage( "手机号码不符合规则");
		
		Boolean bool = false ;
		try {
			bool = userAccountService.isExistUserAccountByMobile(mobile);
			if(bool){
				bool = mobileCodeService.whether(mobile);
				if(bool){
					return ajaxLotterStage("手机验证码已经发送过不要重复发送");
				}
				SiteMessageFormat siteMessageFormat = SiteMessageFormat.RETRIEVE_PWD_NOTICE;
				smsService.sendSms(mobile, siteMessageFormat);
				return ajaxLotterSuccess();
			}else{
				return ajaxLotterUser("号码不存在，请去注册");
			}
		} catch (Exception e) {
			logger.error("验证手机号码有误  请检查");
			return ajaxLotterServer("验证手机号码有误  请联系管理员");
		}
	}
	
	
	/**
	* @Title: register 
	* @Description: 注册
	* @param @param mobile  手机号码  
	* @param @param password 密码
	* @param @param rePassword  重复密码
	* @param @return    设定文件 
	* @return Map<String,Object>    返回类型 
	* @throws
	 */
	@ResponseBody
	@RequestMapping(value="/register",method = RequestMethod.POST)
	public Map<String, Object> register(HttpServletRequest request,
			@RequestParam(value="mobile",required=true) String mobile,
			@RequestParam(value="password",required=true) String password,
    		@RequestParam(value="loginname",required=true) String loginname,
    		@RequestParam(value="smsRandomCode",required=true) String smsRandomCode) {
		if(StringUtil.isBlank(mobile))
			return ajaxLotterStage("手机号码不能为空");
		
		if(StringUtil.isBlank(loginname))
			return ajaxLotterStage("登录名不能为空");
		
		if(StringUtil.isNumeric(loginname))
			return ajaxLotterStage("登录名不能全是数字");
		
		if(StringUtil.isBlank(password))
			return ajaxLotterStage("密码不能为空");
		
		if (mobile.trim().length() != 11) 
			return ajaxLotterStage("手机号码位数不是11位");
		
		if (!mobile.matches(YcContext.Mobile_PARTTEN))
			return ajaxLotterStage( "手机号码不符合规则");
		
		if(password.length() < 6 )
			return ajaxLotterStage("密码必须输入6位及以上字符");
		
		if(StringUtil.isBlank(smsRandomCode))
			return ajaxLotterStage("手机短信验证码");
		
		Boolean bool = false ;
		try {
			String code = smsService.findMobileCode(mobile);
			if(StringUtil.isBlank(code))
				return ajaxLotterUser("手机短信已经过期");
			
			if(!smsRandomCode.equals(code)){
				return ajaxLotterUser("手机短信验证码不正确");
			}
			
			//验证手机号码
			bool = userAccountService.isExistUserAccountByMobile(mobile);
			
			if(!bool){
				//验证登录名
				bool = userAccountService.isExistUserAccountByLoginName(loginname);
				
				if(bool){
					return ajaxLotterUser("用户名已经存在，请进行注册");
				}
				
				userAccountService.saveUserAccountByModel(mobile, password,loginname);
			}else{
				return ajaxLotterUser("手机号码已经存在，请登录");
			}
			
		} catch (Exception e) {
			logger.error("验证手机号码有误  请检查");
			return ajaxLotterServer("服务器异常,请联系管理员");
		}
		
		return ajaxLotterSuccess();
	}
	
	
	/**
	 * 登录查询缓存
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/trun",method = RequestMethod.GET)
	public Map<String, Object> login(HttpServletRequest request,
			@RequestParam(value="token",required=false)String token) {
		Map<String,Object> result = new HashMap<String, Object>();
		if(StringUtil.isBlank(token)){
			result.put("isLogin", 0);
			return ajaxLotterSuccess(result);
		}
		Boolean bool =StaticDataContext.isExist(token);
		if(bool){
			result.put("isLogin", 1);
			return ajaxLotterSuccess(result);
		}
		result.put("isLogin", 0);
		return ajaxLotterSuccess(result);
	}
	
	/**
	* @Title: login 
	* @Description: 登录 
	* @param @param mobile
	* @param @param password
	* @param @return    设定文件 
	* @return Map<String,Object>    返回类型 
	* @throws
	 */
	@ResponseBody
	@RequestMapping(value="/login",method = RequestMethod.POST)
	public Map<String, Object> login(@RequestParam(value="username",required=true) String username,
			@RequestParam(value="password",required=true) String password) {
		Map<String,Object> result =  new HashMap<String, Object>();
		
		if(StringUtil.isBlank(username))
			return ajaxLotterStage("登录名不能为空");
		
		if(StringUtil.isBlank(password))
			return ajaxLotterStage("密码不能为空");
		
		if(password.length() < 6 )
			return ajaxLotterStage("密码必须输入6位及以上字符");
		try {
			int number = userAccountService.countUserByUsername(username);
			if(number == 0){
				return ajaxLotterStage("没有此账户");
			}
			UserAccount userAccount = userAccountService.findUserAccountByMap(username, password);
			if(userAccount == null){
				return ajaxLotterStage("密码出错");
			}
			String token = RoomUtil.createRandomToken();
			userAccountService.updateloginUserAccount(result, userAccount.getId(),token,userAccount.getMobile());
		 } catch (LotterCusException e) {
			logger.error("登录有误,请检查代码");
			return ajaxLotterServer("登录有误,请检查代码");
	     }
		return ajaxLotterSuccess(result);
		
	}
	
	
	/**
	 * 找回密码  下一步
	 * @param request
	 * @param mobile  手机号码
	 * @param smsRandomCode  手机验证码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/retrievePwd_Next",method = RequestMethod.POST)
    public Map<String, Object> retrievePwd_Next(HttpServletRequest request,
    		@RequestParam(value="mobile",required=true) String mobile,
    		@RequestParam(value="smsRandomCode",required=true) String smsRandomCode){
    	if(StringUtil.isBlank(mobile))
			return ajaxLotterStage("手机号码不能为空");
    	if (mobile.trim().length() != 11) 
			return ajaxLotterStage("手机号码位数不是11位");
		
		if (!mobile.matches(YcContext.Mobile_PARTTEN))
			return ajaxLotterStage( "手机号码不符合规则");
		
		if(StringUtil.isBlank(smsRandomCode))
			return ajaxLotterStage("验证码不能为空");
    	
		if(!StringUtil.isNumeric(smsRandomCode))
			return ajaxLotterStage("验证码必须都是数字");
		
		if(smsRandomCode.length() != 6)
			return ajaxLotterStage("验证码数字必须是6位");
		
		Boolean bool = false ;
		try {
			String code = smsService.findMobileCode(mobile);
			if(StringUtil.isBlank(code))
				return ajaxLotterUser("手机短信已经过期");
			
			if(!smsRandomCode.equals(code)){
				return ajaxLotterUser("手机短信验证码不正确");
			}
			
			//验证手机号码
			bool = userAccountService.isExistUserAccountByMobile(mobile);
			if(!bool){
				return ajaxLotterUser("手机号码不存在");
			}
		}catch(LotterCusException e){
			logger.error("找回密码业务查询失败，请检查代码");
			return ajaxLotterServer("服务器异常,请联系管理员");
		}
		
    	return ajaxLotterSuccess();
    }
	
	
	/**
	 * 更新密码
	 * @param request
	 * @param mobile
	 * @param password
	 * @param smsRandomCode
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/updatePwd",method = RequestMethod.POST)
	public Map<String,Object> updatePwd(HttpServletRequest request,
    		@RequestParam(value="mobile",required=true) String mobile,
    		@RequestParam(value="password",required = true) String password,
    		@RequestParam(value="smsRandomCode",required=true) String smsRandomCode){
		
    	if(StringUtil.isBlank(mobile))
			return ajaxLotterStage("手机号码不能为空");
    	if (mobile.trim().length() != 11) 
			return ajaxLotterStage("手机号码位数不是11位");
		
		if (!mobile.matches(YcContext.Mobile_PARTTEN))
			return ajaxLotterStage( "手机号码不符合规则");
		
		if(StringUtil.isBlank(smsRandomCode))
			return ajaxLotterStage("验证码不能为空");
    	
		if(!StringUtil.isNumeric(smsRandomCode))
			return ajaxLotterStage("验证码必须都是数字");
		
		if(smsRandomCode.length() != 6)
			return ajaxLotterStage("验证码数字必须是6位");
		
    	if(StringUtil.isBlank(password))
			return ajaxLotterStage("新密码不能为空");
    	
    	if(password.length() < 6)
    		return ajaxLotterStage("新密码位数不能小于6位");
    	
		Boolean bool = false ;
		try {
			
			String code = smsService.findMobileCode(mobile);
			if(StringUtil.isBlank(code))
				return ajaxLotterUser("手机短信已经过期");
			
			if(!smsRandomCode.equals(code)){
				return ajaxLotterUser("手机短信验证码不正确");
			}
			
			//验证手机号码
			bool = userAccountService.isExistUserAccountByMobile(mobile);
			if(!bool){
				return ajaxLotterUser("手机号码不存在");
			}else{
				userAccountService.updatePwdByMobile(password, mobile);
			}
		}catch(LotterCusException e){
			logger.error("找回密码业务查询失败，请检查代码");
			return ajaxLotterServer("服务器异常,请联系管理员");
		}
		return ajaxLotterSuccess();
	}
	
	
	
	
	
}
